<?php
// +----------------------------------------------------------------------
// | CatchAdmin [Just Like ～ ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~{$year} http://catchadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://github.com/yanwenwu/catch-admin/blob/master/LICENSE.txt )
// +----------------------------------------------------------------------
// | Author: JaguarJack [ njphper@gmail.com ]
// +----------------------------------------------------------------------

namespace catchAdmin\wechatopen;

use catchAdmin\wechatopen\model\Applet;
use catchAdmin\wechatopen\model\Wechatopen as wechatopenModel;
use catcher\ModuleService;
use EasyWeChat\Factory;
use EasyWeChat\MiniProgram\Application as MiniProgram;
use EasyWeChat\OfficialAccount\Application as OfficialAccount;
use EasyWeChat\OpenPlatform\Application as OpenPlatform;
use EasyWeChat\OpenPlatform\Application;
use EasyWeChat\Payment\Application as Payment;
use EasyWeChat\Work\Application as Work;
use think\facade\Cache;
use uctoo\ThinkEasyWeChat\CacheBridge;
use think\facade\Log;
use think\facade\Db;
use uctoo\ThinkEasyWeChat\Facade;

class WechatopenService extends ModuleService
{

    public function register()
    {
        parent::register(); // TODO: Change the autogenerated stub

        $this->registerWechatSDK();
    }

    public function loadRouteFrom()
    {
        // TODO: Implement loadRouteFrom() method.
        return __DIR__ . DIRECTORY_SEPARATOR . 'route.php';
    }

    /**
     * WechatSDK注册
     *
     * @time 2021年03月15日
     * @return void
     */
    protected function registerWechatSDK()
    {
        $apps = [
            'official_account' => OfficialAccount::class,
            'work' => Work::class,
            'mini_program' => MiniProgram::class,
            'payment' => Payment::class,
        ];
        $wechat_default = config('wechat.default') ? config('wechat.default') : [];
        $wechatopen = Db::name('wechatopen')->where('status', 1)->find(); //config('wechat.open_platform.default');  //TODO:读取第三方平台信息表中第一条状态为1的数据
        $wechatopenConfig = [
            'app_id'  => $wechatopen['appid'],
            'secret'  => $wechatopen['appsecret'],
            'token'   => $wechatopen['token'],
            'aes_key' => $wechatopen['encodingAesKey'],
            'oauth' => [
                'scopes'  =>['snsapi_login'],
                'callback'  => 'admin/index/wxlogin_callback',
            ]
        ];
        //合并配置文件
        $account_config = array_merge($wechatopenConfig, $wechat_default);
        Cache::set('wechatopen_config',$account_config);            //第三方平台参数加入缓存，后续如需使用可以从缓存获取配置

        $wechatopen_app =  Factory::openPlatform($account_config);
        $wechatopen_app->rebind('cache',app('cache'));
        $this->app->bind(Application::class,$wechatopen_app);


    }

}
